#include "myframe.h"
#include <QDateTime>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
#include "InterfaceManager.h"
#include "paywindow.h"
#include "system.h"
#include "ui_userordertestwindow.h"
#include "userordertestwindow.h"

MyFrame::MyFrame(int user_id,
                 int order_id,
                 QString orderNumber,
                 QString departureTime,
                 QString arrivalTime,
                 QString departureCity,
                 QString arrivalCity,
                 QString aircraftModel,
                 QString ticketType,
                 QString ticketPrice,
                 QString order_status,
                 QWidget *parent)
    : QFrame(parent)
    , label(nullptr)
    , orderNumber(orderNumber)
    , departureTime(departureTime)
    , arrivalTime(arrivalTime)
    , departureCity(departureCity)
    , arrivalCity(arrivalCity)
    , aircraftModel(aircraftModel)
    , ticketType(ticketType)
    , ticketPrice(ticketPrice)
    , order_status(order_status)
    , cancelButton(nullptr)
    , changeButton(nullptr)
    , payButton(nullptr)
    , layout(nullptr)
    , user_id(user_id)
    , order_id(order_id)
    , manager(new QNetworkAccessManager(this))
{
    setStyleSheet("QFrame { border: 0.5px solid black; }");

    // 创建控件
    label = new QLabel(this);
    QString orderText = "订单号: " + orderNumber
                        + "\n"
                          "出发时间: "
                        + departureTime
                        + "        "
                          "到达时间: "
                        + arrivalTime
                        + "\n"
                          "出发城市: "
                        + departureCity
                        + "        "
                          "到达城市: "
                        + arrivalCity
                        + "\n"
                          "飞机型号: "
                        + aircraftModel
                        + "\n"
                          "票型: "
                        + ticketType
                        + "                     "
                          "票价: "
                        + ticketPrice + "\n";
    label->setText(orderText);
    label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    /*
    // 创建一个字体对象，设置字体大小
    QFont font = label->font();
    font.setPointSize(16);  // 设置字体大小为16

    // 将字体应用到 QLabel
    label->setFont(font);
*/

    if (order_status == "Paid") {
        //如果已经支付完成了
        // 创建两个按钮，分别为 "退票" 和 "改签"
        cancelButton = new QPushButton("退票", this);
        changeButton = new QPushButton("改签", this);
        cancelButton->setFixedSize(75, 23);
        changeButton->setFixedSize(75, 23);

        // 创建布局
        layout = new QVBoxLayout(this);

        // 将控件添加到布局中
        layout->addWidget(label);
        layout->addWidget(cancelButton);
        layout->addWidget(changeButton);

        // 连接按钮的点击信号到槽函数，并传递 user_id 和 flight_id
        connect(cancelButton, &QPushButton::clicked, [this, user_id, order_id]() {
            onCancelButtonClicked(user_id, order_id);
        });

        connect(changeButton, &QPushButton::clicked, [this, user_id, order_id]() {
            onChangeButtonClicked(user_id, order_id);
        });
    } else if (order_status == "Unpaid") {
        payButton = new QPushButton("支付", this);
        payButton->setFixedSize(75, 23);

        // 创建布局
        layout = new QVBoxLayout(this);

        // 将控件添加到布局中
        layout->addWidget(label);
        layout->addWidget(payButton);

        // 连接支付按钮的点击信号到槽函数，并传递 user_id 和 flight_id
        connect(payButton, &QPushButton::clicked, [this, user_id, order_id]() {
            onPayButtonClicked(user_id, order_id);
        });
    }

    // 设置布局
    setLayout(layout);

    // 设置窗口固定大小
    setFixedSize(650, 180); // 设置固定大小为 650x180
}

MyFrame::~MyFrame()
{
    // 析构函数，确保所有动态分配的内存得到释放
}

void MyFrame::onCancelButtonClicked(int user_id, int order_id)
{
    qDebug() << "Cancel button clicked, User ID:" << user_id << ", Order ID:" << order_id;

    QMessageBox::StandardButton reply = QMessageBox::question(this,
                                                              "确认退票",
                                                              "您确定要退票吗？",
                                                              QMessageBox::Yes | QMessageBox::No);

    // 如果用户点击了 "Yes"，执行退票操作
    if (reply == QMessageBox::Yes) {
        // 处理退票逻辑

        // // 创建 QNetworkAccessManager 用于发送请求
        // QNetworkAccessManager *manager = new QNetworkAccessManager(this);

        // // 创建 URL 和请求对象  /api/orders/refund
        // QUrl url("http://127.0.0.1:8080/api/orders/refund"); // 替换为实际 API 地址
        // QNetworkRequest request(url);

        // // 设置请求头
        // request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        // // 构建 JSON 请求体
        // QJsonObject requestBody;
        // requestBody["id"] = order_id;
        // requestBody["order_status"] = "Cancelled";
        // requestBody["refund_time"] = QDateTime::currentSecsSinceEpoch(); // 当前时间戳

        // QJsonDocument doc(requestBody);
        // QByteArray jsonData = doc.toJson();

        // // 发送 POST 请求
        // QNetworkReply *reply = manager->post(request, jsonData);

        // // 连接信号和槽函数，处理响应
        // connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        //     // 获取响应内容
        //     QByteArray responseData = reply->readAll();
        //     QJsonDocument responseDoc = QJsonDocument::fromJson(responseData);
        //     QJsonObject responseObj = responseDoc.object();

        //     // 检查响应状态码
        //     int code = responseObj["code"].toInt();
        //     if (code == 200) {
        //         // 订单取消成功
        //         qDebug() << "Order Cancelled successfully, Order ID:"
        //                  << responseObj["data"].toObject()["id"].toInt();
        //         QMessageBox::information(nullptr, "提示", "退票成功！");
        //     } else {
        //         // 订单取消失败
        //         qDebug() << "Order cancellation failed:" << responseObj["message"].toString();
        //         QMessageBox::information(nullptr, "提示", "退票失败，请稍后重试！");
        //     }
        //     // 清理回复对象
        //     reply->deleteLater();*/

        // 构建 JSON 请求体
        QJsonObject requestBody;
        requestBody["id"] = order_id;
        requestBody["order_status"] = "Cancelled";
        requestBody["refund_time"] = QDateTime::currentSecsSinceEpoch(); // 当前时间戳

            // 将 JSON 对象转换为 JSON 文档
            QJsonDocument doc(requestBody);
            QByteArray data = doc.toJson();

            // 设置请求头
            QNetworkRequest request(QUrl("http://127.0.0.1:8080/api/orders/refund")); // 替换为你的 API URL
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

            // 发送 POST 请求
            QNetworkReply *reply = manager->post(request, data);

            // 连接请求完成信号
            connect(reply, &QNetworkReply::finished, this, &MyFrame::onRefundRequestFinished);

    } else {
        // 如果用户选择了 "No"，则取消退票操作
        qDebug() << "Order cancellation cancelled.";
    }

}

    void MyFrame::onRefundRequestFinished(){

        QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

        // 如果请求失败，输出错误信息
        if (reply->error() != QNetworkReply::NoError) {
            QString errorString = reply->errorString(); // 获取错误信息
            qDebug() << "Request failed with error:" << errorString;
            QMessageBox::critical(this, "Error", "Refund request failed: " + errorString);
            reply->deleteLater();
            return;
        }

        // 请求成功，处理响应数据
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);
        QJsonObject jsonResponse = doc.object();

        // 处理响应
        int code = jsonResponse["code"].toInt();
        if (code == 200) {
            // 退票成功
            QMessageBox::information(this, "Success", "Refund successful!");

            InterfaceManager ::instance()->unregisterPage("/MainWindow/First/Order");
            UserordertestWindow *orderwindow1 = new UserordertestWindow();
            InterfaceManager::instance()->registerPage("/MainWindow/First/Order", orderwindow1);
            InterfaceManager::instance()->switchToPage("/MainWindow/First/Order");

        }
    }

void MyFrame::onChangeButtonClicked(int user_id, int order_id)
{
    qDebug() << "Change button clicked, User ID:" << user_id << ", Order ID:" << order_id;
    // 处理改签逻辑
}

void MyFrame::onPayButtonClicked(int user_id, int order_id)
{
    qDebug() << "Pay button clicked, User ID:" << user_id << ", Order ID:" << order_id;
    PayWindow *pw = new PayWindow(this, user_id, order_id);
    pw->show();

    InterfaceManager ::instance()->unregisterPage("/MainWindow/First/Order");
    UserordertestWindow *orderwindow1 = new UserordertestWindow();
    InterfaceManager::instance()->registerPage("/MainWindow/First/Order", orderwindow1);
    InterfaceManager::instance()->switchToPage("/MainWindow/First/Order");
}
